<template>
  <div class="page">
    <!-- 顶部 开始 -->
    <div class="top_info">
      <div class="cell">
        <div class="title"><span>常用功能</span></div>
        <div class="a_list">

          <div class="a_box" v-for="(item,index) in linkList" :key="index" @click="linkUrlEvent(item)">
            <div class="icon">
              <img :src="require('@/assets/images/' + item.icon)" alt="" />
              <div class="dot" v-if="todoInfo[item.id]">{{todoInfo[item.id]}}</div>
            </div>
            <div class="name">{{item.name}}</div>
          </div>

          <!-- <div class="a_box" @click="addCustomer">
            <div class="icon">
              <img src="@/assets/images/link_01.png" alt="" />
            </div>
            <div class="name">新增客户</div>
          </div>

          <div class="a_box" @click="addBook">
            <div class="icon">
              <img src="@/assets/images/link_02.png" alt="" />
            </div>
            <div class="name">新增预约</div>

          </div>

          <div class="a_box" @click="linkUrlEvent('/customer/book',{num:todoInfo.waOverdueCustomerCnt})">
            <div class="icon">
              <img src="@/assets/images/link_09.png" alt="" />
              <div class="dot" v-if="todoInfo.waOverdueCustomerCnt">{{todoInfo.waOverdueCustomerCnt}}</div>
            </div>
            <div class="name">待预约客户</div>
          </div>

          <div class="a_box" @click="linkUrlEvent('/customer/unsettled',{num:todoInfo.udOverdueCustomerCnt})">
            <div class="icon">
              <img src="@/assets/images/link_10.png" alt="" />
              <div class="dot" v-if="todoInfo.udOverdueCustomerCnt">{{todoInfo.udOverdueCustomerCnt}}</div>
            </div>
            <div class="name">未成交客户</div>
          </div>

          <div class="a_box" @click="linkUrlEvent('/customer/contact')">
            <div class="icon">
              <img src="@/assets/images/link_05.png" alt="" />
              <div class="dot" v-if="todoInfo.waitContactedCnt">{{todoInfo.waitContactedCnt}}</div>
            </div>
            <div class="name">待联系客户</div>
          </div>

          <div class="a_box" @click="linkUrlEvent('/book/visit')">
            <div class="icon">
              <img src="@/assets/images/link_06.png" alt="" />
              <div class="dot" v-if="todoInfo.waitReturnVisitCnt">{{todoInfo.waitReturnVisitCnt}}</div>
            </div>
            <div class="name">待回访预约</div>

          </div>

          <div class="a_box" @click="linkUrlEvent('/book/expired')">
            <div class="icon">
              <img src="@/assets/images/link_07.png" alt="" />
              <div class="dot" v-if="todoInfo.expireCustomerCnt">{{todoInfo.expireCustomerCnt}}</div>
            </div>
            <div class="name">待更新预约</div>

          </div>

          <div class="a_box" @click="linkUrlEvent('/system/todo')">
            <div class="icon">
              <img src="@/assets/images/link_08.png" alt="" />
              <div class="dot" v-if="todoInfo.waitTodoNoticeCnt">{{todoInfo.waitTodoNoticeCnt}}</div>
            </div>
            <div class="name">待办通知</div>
          </div> -->
        </div>
      </div>
      <div class="cell">
        <div class="title">
          <span>本月进度</span>
          <div class="link" @click="openDialog()">
            <span class="sp1">设置目标</span><i class="el-icon-arrow-right"></i>
          </div>
        </div>
        <div class="plan_box">
          <div class="line">
            <div class="pre">
              <span>预约</span>
              <span class="sp1">{{targetInfo.actualAppointmentCnt}}人</span>
            </div>
            <div class="process">
              <el-progress :text-inside="false" :stroke-width="10" :percentage="targetInfo.appointmentReachRate?Number(targetInfo.appointmentReachRate.toFixed(0)):0"></el-progress>
            </div>
            <span class="sp2">目标：{{targetInfo.appointmentCnt}}人</span>
          </div>
          <div class="line">
            <div class="pre">
              <span>新成交</span>
              <span class="sp1">{{showNumber(targetInfo.actualNewDealAmount)}}万</span>
            </div>

            <div class="process">
              <el-progress :text-inside="false" :stroke-width="10" :percentage="targetInfo.newDealAmountReachRate?Number(targetInfo.newDealAmountReachRate.toFixed(0)):0"></el-progress>
            </div>
            <span class="sp2">目标：{{targetInfo.newDealAmount}}万</span>
          </div>
          <div class="line">
            <div class="pre">
              <span>收款</span>
              <span class="sp1">{{showNumber(targetInfo.actualCollectMoney)}}万</span>
            </div>

            <div class="process">
              <el-progress :text-inside="false" :stroke-width="10" :percentage="targetInfo.collectMoneyReachRate?Number(targetInfo.collectMoneyReachRate.toFixed(0)):0"></el-progress>
            </div>
            <span class="sp2">目标：{{targetInfo.collectMoney}}万</span>
          </div>
        </div>
      </div>
      <div class="cell">
        <div class="title"><span>本月排行榜</span></div>
        <div class="div_tab">
          <div class="tab_head">
            <div class="th">排名</div>
            <div class="th">姓名</div>
            <div class="th" v-for="(item,index) in thList" :key="index" :class="orderType == item.id?'cblue':''" @click="thEvent(item,index)">{{item.name}}<i :class="item.active?'el-icon-caret-top':'el-icon-caret-bottom'"></i></div>
            <!-- <div class="th" :class="orderType == 1?'cblue':''" id="1" @click="thEvent(1)">预约<i :class="orderType == 1?'el-icon-caret-top':'el-icon-caret-bottom'"></i></div>
            <div class="th" :class="orderType == 2?'cblue':''" id="2" @click="thEvent(2)">成交<i :class="orderType == 2?'el-icon-caret-top':'el-icon-caret-bottom'"></i></div>
            <div class="th" :class="orderType == 3?'cblue':''" id="3" @click="thEvent(3)">收款<i :class="orderType == 3?'el-icon-caret-top':'el-icon-caret-bottom'"></i></div> -->
          </div>
          <div class="tab_tr" v-for="(item,index) in resultList" :key="index">
            <div class="td">
              <img :src="iconList[index+1]" class="img" alt="">
            </div>
            <div class="td">{{item.name}}</div>
            <div class="td" :class="orderType == 1?'cblue':''">{{item.appointmentCnt}}</div>
            <div class="td" :class="orderType == 2?'cblue':''">{{item.dealAmount}}</div>
            <div class="td" :class="orderType == 3?'cblue':''">{{item.collectMoney}}</div>
          </div>
        </div>
      </div>
    </div>
    <!-- 顶部 end -->

    <!-- 今日数据 开始 -->
    <div class="today_info">
      <div class="title">
        <span>今日数据</span>
        <span class="time">更新时间：{{updateTime}}</span>
      </div>
      <div class="cell_list">
        <div class="cell" v-for="(item, index) in todayList" :key="`idx_${index}`">
          <div class="h1">{{ item.name }}</div>
          <div class="h2">{{ item.num?Number(item.num).toFixed(0):0}}{{item.id == 'appointmentRate' || item.id == 'appointmentArrivedRate'|| item.id == 'arrivedDealRate'?'%':''}}</div>
          <div class="h3">昨日{{ item.yesterday?Number(item.yesterday).toFixed(0):0 }}{{item.id == 'appointmentRate' || item.id == 'appointmentArrivedRate'|| item.id == 'arrivedDealRate'?'%':''}}</div>
        </div>
      </div>
    </div>
    <!-- 今日数据 end -->

    <!-- 本周数据 开始 -->
    <div class="today_info">
      <div class="title">
        <span>本周数据</span>
        <span class="time">更新时间：{{updateTime}}</span>
      </div>
      <div class="cell_list">
        <div class="cell" v-for="(item, index) in weekDataList" :key="`idx_${index}`">
          <div class="h1">{{ item.name }}</div>
          <div class="h2">{{ item.num?Number(item.num).toFixed(0):0}}{{item.id == 'appointmentRate' || item.id == 'appointmentArrivedRate'|| item.id == 'arrivedDealRate'?'%':''}}</div>
          <div class="h3">上周{{ item.yesterday?Number(item.yesterday).toFixed(0):0 }}{{item.id == 'appointmentRate' || item.id == 'appointmentArrivedRate'|| item.id == 'arrivedDealRate'?'%':''}}</div>
        </div>
      </div>
    </div>
    <!-- 本周数据 end -->

    <!-- 本月数据 开始 -->
    <div class="today_info">
      <div class="title">
        <span>本月数据</span>
        <span class="time">更新时间：{{updateTime}}</span>
      </div>
      <div class="cell_list">
        <div class="cell" v-for="(item, index) in monthDataList" :key="`idx_${index}`">
          <div class="h1">{{ item.name }}</div>
          <div class="h2">
            {{ item.num?Number(item.num).toFixed(0):0}}
            {{item.id == 'appointmentRate' || item.id == 'appointmentArrivedRate'|| item.id == 'arrivedDealRate'?'%':''}}
            <i :class="`el-icon-caret-${
                item.status == 1 ? 'bottom cgreen' : 'top cred'
              }`" v-if="item.status"></i>
          </div>
          <div class="h3">上月{{ item.yesterday?Number(item.yesterday).toFixed(0):0 }}{{item.id == 'appointmentRate' || item.id == 'appointmentArrivedRate'|| item.id == 'arrivedDealRate'?'%':''}}</div>
        </div>
      </div>
    </div>
    <!-- 本月数据 end -->

    <!-- 转化率  开始 -->
    <div class="today_info change_rate">
      <div class="title">
        <div class="left">
          <span>{{showRateTime(dealTime)}}月转化率</span>
          <span class="time">更新时间：{{updateTime}}</span>
        </div>
        <div class="right">
          <el-date-picker v-model="dealTime" size="mini" type="month" placeholder="选择月" class="a_input" value-format="yyyy-MM" @change="getMonthRate">
          </el-date-picker>
        </div>
      </div>

      <div class="chart_info">
        <div class="top">
          <div class="k"></div>
          <div class="tab_head">
            <div class="th">我的转化率</div>
            <div class="th">最佳转化率</div>
            <div class="th">平均转化率</div>
          </div>
        </div>
        <div class="bottom">
          <div class="k">
            <img src="@/assets/images/chart.png" alt="" />
          </div>
          <div class="tab_box">
            <div class="tab_tr">
              <div class="td">
                <div>客户数</div>
                <div class="t1">{{myRateInfo.customerCnt||0}}</div>
              </div>
              <div class="td">
                <div>客户数</div>
                <div class="t1">{{bestRateInfo.customerCnt||0}}</div>
              </div>
              <div class="td">
                <div>客户数</div>
                <div class="t1">{{meanRateInfo.customerCnt||0}}</div>
              </div>
            </div>
            <div class="tab_tr">
              <div class="td">
                <div>客户预约率</div>
                <div class="t1">{{myRateInfo.appointmentRate?myRateInfo.appointmentRate.toFixed(0):0}}%</div>
              </div>
              <div class="td">
                <div>客户预约率</div>
                <!-- <div class="t1">{{bestRateInfo.appointmentRate?bestRateInfo.appointmentRate.toFixed(0):0}}%</div> -->
                <div class="t1">78%</div>
              </div>
              <div class="td">
                <div>客户预约率</div>
                <div class="t1">{{meanRateInfo.appointmentRate?meanRateInfo.appointmentRate.toFixed(0):0}}%</div>
              </div>
            </div>
            <div class="tab_tr">
              <div class="td">
                <div>预约到店率</div>
                <div class="t1">{{myRateInfo.appointmentArrivedRate?Number(myRateInfo.appointmentArrivedRate).toFixed(0):0}}%</div>
              </div>
              <div class="td">
                <div>预约到店率</div>
                <!-- <div class="t1">{{bestRateInfo.appointmentArrivedRate?Number(bestRateInfo.appointmentArrivedRate).toFixed(0):0}}%</div> -->
                <div class="t1">83%</div>
              </div>
              <div class="td">
                <div>预约到店率</div>
                <div class="t1">{{meanRateInfo.appointmentArrivedRate?Number(meanRateInfo.appointmentArrivedRate).toFixed(0):0}}%</div>
              </div>
            </div>
            <div class="tab_tr">
              <div class="td">
                <div>到店成交率</div>
                <div class="t1">{{myRateInfo.arrivedDealRate?Number(myRateInfo.arrivedDealRate).toFixed(0):0}}%</div>
              </div>
              <div class="td">
                <div>到店成交率</div>
                <!-- <div class="t1">{{bestRateInfo.arrivedDealRate?Number(bestRateInfo.arrivedDealRate).toFixed(0):0}}%</div> -->
                <div class="t1">90%</div>
              </div>
              <div class="td">
                <div>到店成交率</div>
                <div class="t1">{{meanRateInfo.arrivedDealRate?Number(meanRateInfo.arrivedDealRate).toFixed(0):0}}%</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 转化率  end -->

    <!-- 设置目标 开始 -->
    <glsx-dialog :show="showDialog" title="本月目标设置" @close="closeDialog()">
      <div class="target_box">
        <el-form :model="addForm" ref="addForm" :rules="addFormRules" label-width="120px">
          <el-form-item label="预约人数：" prop="appointmentCnt">
            <el-input placeholder="请输入" v-model.number="addForm.appointmentCnt" class="a_input">
              <template slot="append">人</template>
            </el-input>
          </el-form-item>
          <el-form-item label="新成交金额：" prop="dealAmount">
            <el-input placeholder="请输入" v-model="addForm.dealAmount" class="a_input">
              <template slot="append">万</template>
            </el-input>
          </el-form-item>
          <el-form-item label="收款金额：" prop="collectMoney">
            <el-input placeholder="请输入" v-model="addForm.collectMoney" class="a_input">
              <template slot="append">万</template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveTarget">保存</el-button>
          </el-form-item>
        </el-form>
      </div>
    </glsx-dialog>
    <!-- 设置目标 end -->

  </div>
</template>

<script>
import {
  GETSALETODODATA,
  GETSALEMONTHTARGETPROGRESS,
  GETSALEPERFORMANCERANKING,
  GETSALETODAYDATA,
  GETSALEMONTHDATA,
  GETSALEWEEKDATA,
  GETSALEMONTHCONVERSION,
  SETUPTARGETINFO,
} from "@/http/system";
import { broadcast, deepClone, showToast } from "@/common/util";
import moment from "moment";
import GlsxDialog from "@/components/Dialog/index";
import { Validator } from "@/common/validator";
export default {
  components: {
    GlsxDialog,
  },
  data() {
    return {
      linkList: [
        {
          icon: "link_05.png",
          name: "待联系客户",
          id: "waitContactedCnt",
          url: "/customer/contact",
        },
        {
          icon: "link_07.png",
          name: "待更新预约",
          id: "expireCustomerCnt",
          url: "/book/expired",
        },
        {
          icon: "link_06.png",
          name: "待回访预约",
          id: "waitReturnVisitCnt",
          url: "/book/visit",
        },
        {
          icon: "link_11.png",
          name: "待提醒预约",
          id: "waitRemindCnt",
          url: "/book/undue",
        },
        {
          icon: "link_10.png",
          name: "未成交跟进",
          id: "udOverdueCustomerCnt",
          url: "/customer/unsettled",
        },
        {
          icon: "link_09.png",
          name: "待预约跟进",
          id: "waOverdueCustomerCnt",
          url: "/customer/book",
        },
        {
          icon: "link_12.png",
          name: "待收尾款",
          id: "waitToCollectCnt",
          url: "/deal/record",
        },
        {
          icon: "link_08.png",
          name: "待办提醒",
          id: "waitTodoNoticeCnt",
          url: "/system/todo",
        },
      ],
      todayList: [
        { name: "新增客户数", num: 32, yesterday: 22, id: "newCustomerCnt" },
        { name: "新增预约数", num: 7, yesterday: 22, id: "appointmentCnt" },
        { name: "应到店预约数", num: 7, yesterday: 22, id: "shouldArrivedCnt" },
        { name: "新增到店数", num: 7, yesterday: 22, id: "arrivedCnt" },
        { name: "新增成交数", num: 7, yesterday: 22, id: "arrivedDealCnt" },
        { name: "新增成交金额", num: 7333, yesterday: 22, id: "dealAmount" },
        { name: "新增收款金额", num: 7333, yesterday: 22, id: "collectMoney" },
        { name: "新增退款金额", num: -100, yesterday: 22, id: "refundMoney" },
        {
          name: "平均客单价",
          num: 8999,
          yesterday: 22,
          id: "averageCustomerUnitPrice",
        },
        {
          name: "线索预约率",
          num: "72%",
          yesterday: 22,
          id: "appointmentRate",
        },
        {
          name: "预约到店率",
          num: "72%",
          yesterday: 22,
          id: "appointmentArrivedRate",
        },
        {
          name: "到店成交率",
          num: "72%",
          yesterday: 22,
          id: "arrivedDealRate",
        },
      ],
      monthDataList: [],
      weekDataList: [],
      value: "",
      todoInfo: {},
      targetInfo: {},
      resultList: [],
      myRateInfo: {},
      bestRateInfo: {},
      meanRateInfo: {},
      dealTime: "",
      updateTime: "",
      month: "",
      showDialog: false,
      addForm: {},
      addFormRules: {
        appointmentCnt: [
          { required: true, message: "请输入预约人数", trigger: "blur" },
          { type: "number", message: "请输入数字", trigger: "blur" },
        ],
        dealAmount: [
          { required: true, message: "请输入新成交金额", trigger: "blur" },
          {
            pattern: Validator.TWODECIMAL,
            message: "请输入正确的新成交金额",
            trigger: "blur",
          },
        ],
        collectMoney: [
          { required: true, message: "请输入收款金额", trigger: "blur" },
          {
            pattern: Validator.TWODECIMAL,
            message: "请输入正确的收款金额",
            trigger: "blur",
          },
        ],
      },
      orderType: 2,
      iconList: {
        1: require("@/assets/images/icon_one.png"),
        2: require("@/assets/images/icon_two.png"),
        3: require("@/assets/images/icon_three.png"),
        4: require("@/assets/images/icon_four.png"),
        5: require("@/assets/images/icon_five.png"),
      },
      thList: [
        { name: "预约", id: 1, active: false, filed: "appointmentCnt" },
        { name: "成交", id: 2, active: false, filed: "dealAmount" },
        { name: "收款", id: 3, active: false, filed: "collectMoney" },
      ],
    };
  },
  mounted() {
    this.updateTime = moment().format("yyyy/MM/DD HH:mm");
    this.month = moment().format("MM");
    this.dealTime = moment().format("yyyy-MM");
    this.getTodoData();
    this.getMonthTarget();
    this.getResults();
    this.getToday();
    this.getMonthData();
    this.getMonthRate();
    this.getWeekData();
  },
  methods: {
    // 获取代办通知数据
    getTodoData() {
      let _this = this;
      GETSALETODODATA().then((res) => {
        _this.todoInfo = res.data || {};
      });
    },

    // 新增客户
    addCustomer() {
      broadcast("customer.add");
    },

    // 新增预约
    addBook() {
      broadcast("customer.add.book");
    },

    // 收款变动
    addCollect() {
      broadcast("customer.collect.add", { status: 4, title: "收款变动" });
    },

    // 页面跳转
    linkUrlEvent(row) {
      let options = {};
      options.num = this.todoInfo[row.id];
      if (row.id == "waitToCollectCnt") {
        options.dealTypes = "2,3";
      }
      this.$router.push({ path: row.url, query: options });
    },

    // 获取本月目标数据
    getMonthTarget() {
      GETSALEMONTHTARGETPROGRESS().then((res) => {
        this.targetInfo = res.data || {};
      });
    },

    // 获取本月业绩排行榜
    getResults() {
      let _type = this.orderType;
      let oParams = {};
      oParams.orderType = _type;

      let n = this.thList.find((k) => k.id == _type);

      if (n) {
        oParams.orderDirection = n.active ? "ASC" : "DESC";
        oParams.orderField = n.filed;
      }

      GETSALEPERFORMANCERANKING(oParams).then((res) => {
        this.resultList = res.data || [];
      });
    },

    // 获取今日数据
    getToday() {
      GETSALETODAYDATA().then((res) => {
        let obj = res.data || [];
        let t = obj[0] ? obj[0] : [];
        let y = obj[1] ? obj[1] : [];
        this.todayList.map((k) => {
          k.num = t[k.id];
          k.yesterday = y[k.id];
          return k;
        });
      });
    },

    // 获取本周数据
    getWeekData() {
      let _this = this;
      GETSALEWEEKDATA().then((res) => {
        let list = deepClone(_this.todayList);
        let obj = res.data || [];
        let t = obj[0] ? obj[0] : [];
        let y = obj[1] ? obj[1] : [];
        list.map((k) => {
          k.num = t[k.id];
          k.yesterday = y[k.id];
          return k;
        });
        _this.weekDataList = list;
      });
    },

    // 获取本月数据
    getMonthData() {
      let _this = this;
      GETSALEMONTHDATA().then((res) => {
        let list = deepClone(_this.todayList);
        let obj = res.data || [];
        let t = obj[0] ? obj[0] : [];
        let y = obj[1] ? obj[1] : [];
        list.map((k) => {
          k.num = t[k.id];
          k.yesterday = y[k.id];
          return k;
        });
        _this.monthDataList = list;
      });
    },

    // 获取本月转化率
    getMonthRate() {
      let oParams = {};
      oParams.month = this.dealTime;
      GETSALEMONTHCONVERSION(oParams).then((res) => {
        let list = res.data || [];
        this.myRateInfo = list[0] || {};
        this.bestRateInfo = list[1] || {};
        this.meanRateInfo = list[2] || {};
      });
    },

    // 打开弹框
    openDialog() {
      this.showDialog = true;
    },

    // 关闭弹框
    closeDialog() {
      this.$refs.addForm.clearValidate();
      this.showDialog = false;
      this.addForm = {};
    },

    // 保存目标
    saveTarget() {
      let _this = this;
      let oParams = deepClone(_this.addForm);
      _this.$refs.addForm.validate((valid) => {
        if (!valid) {
          return false;
        }
        SETUPTARGETINFO(oParams).then((res) => {
          if (res.code == 200) {
            showToast({
              message: "保存成功",
              type: "success",
            });
            _this.closeDialog();
            _this.getMonthTarget();
          }
        });
      });
    },

    // 数字单位处理
    showNumber(str) {
      let o = Number(str || 0);
      console.log(str);
      return Math.round(o / 10000);
    },

    // 处理月份展示
    showRateTime(str) {
      if (!str) {
        return "";
      }
      let m = moment(str).format("M");
      return m;
    },

    // 切换本月业绩排行榜
    thEvent(row, index) {
      row.active = !row.active;
      this.orderType = row.id;
      this.$set(this.thList, index, row);
      this.getResults();
    },
  },
};
</script>

<style lang="scss" scoped>
@import "index.scss";
.target_box {
  .a_input {
    width: 80%;
  }
}
</style>
